﻿using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;

namespace PDFTools
{
    public partial class PdfSplitFView : UserControl, IPdfTool
    {
        public override string Text
        {
            get { return "拆分PDF"; }
        }

        public PdfSplitFView()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            textBoxOutFolder.Text = Properties.Settings.Default.SplitOutFolder;
            if (Properties.Settings.Default.SplitType == 0)
            {
                radioButtonEachPage.Checked = true;
            }
            else
            {
                radioButtonSpecifiedPages.Checked = true;
            }
        }

        public void SaveProperties()
        {
            Properties.Settings.Default.SplitOutFolder = textBoxOutFolder.Text;
            if (radioButtonEachPage.Checked)
            {
                Properties.Settings.Default.SplitType = 0;
            }
            else
            {
                Properties.Settings.Default.SplitType = 1;
            }
        }


        private void buttonPdfFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
            dialog.Title = "选择PDF文件";
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            textBoxPDF.Text = dialog.FileName;
        }

        private void buttonPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "选择输出文件夹";
            dialog.ShowNewFolderButton = true;
            dialog.RootFolder = Environment.SpecialFolder.Desktop;
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            textBoxOutFolder.Text = dialog.SelectedPath;
        }

        public void Exec()
        {
            if (string.IsNullOrEmpty(textBoxPDF.Text))
            {
                MessageBox.Show("没设置PDF文件！", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(textBoxOutFolder.Text))
            {
                MessageBox.Show("没设置PDF文件输出目录！", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (radioButtonEachPage.Checked)
            {
                SplitPdfEachPage();

                MessageBox.Show($"按页拆分PDF完成，请到目录\n{textBoxOutFolder.Text}\n下查看！", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (radioButtonSpecifiedPages.Checked)
            {
                if (SplitPdfSpecifiedPages())
                    MessageBox.Show($"按页拆分PDF完成，请到目录\n{textBoxOutFolder.Text}\n下查看！", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private bool SplitPdfSpecifiedPages()
        {
            string[] pageStrs = textBoxSpecifiedPages.Text.Split(',');
            using (PdfDocument inputDocument = PdfReader.Open(textBoxPDF.Text, PdfDocumentOpenMode.Import))
            {
                string fileName = Path.GetFileNameWithoutExtension(textBoxPDF.Text);

                foreach (string pageStr in pageStrs)
                {
                    if (string.IsNullOrEmpty(pageStr))
                        continue;

                    if (pageStr.Contains("-"))
                    {
                        string[] pageRange = pageStr.Split('-');
                        if (pageRange.Length != 2)
                        {
                            MessageBox.Show("指定页码格式错误", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        if (!int.TryParse(pageRange[0], out int startPage) || !int.TryParse(pageRange[1], out int endPage))
                        {
                            MessageBox.Show("指定页码格式错误", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        if (startPage < 1 || endPage > inputDocument.PageCount || startPage > endPage)
                        {
                            MessageBox.Show("指定页码范围错误", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        PdfDocument outputDocument = new PdfDocument();
                        for (int i = startPage - 1; i < endPage; i++)
                        {
                            outputDocument.AddPage(inputDocument.Pages[i]);
                        }
                        string outputFileName = System.IO.Path.Combine(textBoxOutFolder.Text, $"{fileName}_{startPage}-{endPage}.pdf");
                        outputDocument.Save(outputFileName);
                    }
                    else
                    {
                        int page;
                        if (!int.TryParse(pageStr, out page))
                        {
                            MessageBox.Show("指定页码格式错误", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        if (page < 1 || page > inputDocument.PageCount)
                        {
                            MessageBox.Show("指定页码范围错误", "拆分PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        PdfDocument outputDocument = new PdfDocument();
                        outputDocument.AddPage(inputDocument.Pages[page - 1]);
                        string outputFileName = System.IO.Path.Combine(textBoxOutFolder.Text, $"{fileName}_{page}.pdf");
                        outputDocument.Save(outputFileName);
                    }

                }
                return true;
            }
        }

        private void SplitPdfEachPage()
        {
            using (PdfDocument inputDocument = PdfReader.Open(textBoxPDF.Text, PdfDocumentOpenMode.Import))
            {
                string fileName = Path.GetFileNameWithoutExtension(textBoxPDF.Text);
                for (int i = 0; i < inputDocument.PageCount; i++)
                {
                    PdfDocument outputDocument = new PdfDocument();
                    outputDocument.AddPage(inputDocument.Pages[i]);
                    string outputFileName = System.IO.Path.Combine(textBoxOutFolder.Text, $"{fileName}_{i + 1}.pdf");
                    outputDocument.Save(outputFileName);
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            //this.DialogResult = DialogResult.Cancel;
            //this.Close();
        }

        private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonSpecifiedPages.Checked)
            {
                textBoxSpecifiedPages.Enabled = true;
            }
            else
            {
                textBoxSpecifiedPages.Enabled = false;
            }
        }
    }
}
